import 'package:flutter/material.dart';
import 'screens/splash_screen.dart';
import '../services/weather_service.dart' as ws;
import 'screens/detail_screen.dart' as ds;
import 'services/city_service.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '天气速览',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
      ),
      home: const SplashScreen(),
    );
  }
}

class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  final TextEditingController _controller = TextEditingController();
  List<String> cityList = ['北京', '上海', '广州']; // 初始城市列表
  Map<String, Map<String, dynamic>?> weatherMap = {}; // 城市名 -> 天气数据

  // 城市与建筑线条图标的映射
  final Map<String, IconData> cityLandmarkIcons = {
    '北京': Icons.account_balance, // 故宫风格
    '上海': Icons.location_city,   // 城市高楼
    '广州': Icons.apartment,      // 广州塔风格
    
  };

  @override
  void initState() {
    super.initState();
    for (var city in cityList) {
      fetchWeather(city);
    }
  }

  Future<void> fetchWeather(String cityName) async {
    final latLng = await CityService.fetchLatLng(cityName);
    if (latLng == null) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('未找到该城市：$cityName')),
        );
      }
      return;
    }
    final realtime = await ws.WeatherService.fetchRealtimeWeather(latLng[0], latLng[1]);
    setState(() {
      weatherMap[cityName] = realtime;
      if (!cityList.contains(cityName)) {
        cityList.add(cityName);
      }
    });
  }

  void onSearch(String value) {
    if (value.isNotEmpty) {
      fetchWeather(value);
      _controller.clear();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.blue[50],
      appBar: AppBar(
        title: const Text('天气速览'),
        backgroundColor: Colors.blue[300],
        elevation: 0,
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            TextField(
              controller: _controller,
              decoration: InputDecoration(
                hintText: '请输入城市名称',
                prefixIcon: Icon(Icons.search, color: Colors.blueGrey[700]),
                filled: true,
                fillColor: Colors.blue[50],
                contentPadding: const EdgeInsets.symmetric(vertical: 14),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(16),
                  borderSide: BorderSide.none,
                ),
              ),
              onSubmitted: onSearch,
            ),
            const SizedBox(height: 20),
            Expanded(
              child: ListView.builder(
                itemCount: cityList.length,
                itemBuilder: (context, index) {
                  final city = cityList[index];
                  final weatherData = weatherMap[city];
                  final icon = cityLandmarkIcons[city] ?? Icons.location_city;

                  return AnimatedScale(
                    scale: weatherData == null ? 1.0 : 1.02,
                    duration: const Duration(milliseconds: 200),
                    child: Card(
                      margin: const EdgeInsets.symmetric(vertical: 10),
                      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(18)),
                      elevation: 8,
                      shadowColor: Colors.blue.withOpacity(0.3),
                      child: InkWell(
                        borderRadius: BorderRadius.circular(18),
                        onTap: weatherData == null
                            ? null
                            : () {
                                Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                    builder: (context) => ds.DetailScreen(city: city, weatherData: weatherData),
                                  ),
                                );
                              },
                        child: Container(
                          height: 120,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(18),
                            gradient: LinearGradient(
                              colors: [Colors.blue[200]!, Colors.white],
                              begin: Alignment.topLeft,
                              end: Alignment.bottomRight,
                            ),
                          ),
                          child: Row(
                            children: [
                              Padding(
                                padding: const EdgeInsets.all(24.0),
                                child: Container(
                                  decoration: BoxDecoration(
                                    color: Colors.white.withOpacity(0.7),
                                    shape: BoxShape.circle,
                                    boxShadow: [
                                      BoxShadow(
                                        color: Colors.blue.withOpacity(0.2),
                                        blurRadius: 12,
                                        offset: Offset(0, 4),
                                      ),
                                    ],
                                  ),
                                  child: Icon(
                                    icon,
                                    size: 60,
                                    color: Colors.blueGrey[700],
                                  ),
                                ),
                              ),
                              Expanded(
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(
                                      city,
                                      style: TextStyle(
                                        fontSize: 28,
                                        fontWeight: FontWeight.bold,
                                        color: Colors.blueGrey[900],
                                        letterSpacing: 1.2,
                                      ),
                                    ),
                                    const SizedBox(height: 8),
                                    weatherData == null
                                        ? Text(
                                            '加载中...',
                                            style: TextStyle(color: Colors.blueGrey[600], fontSize: 16),
                                          )
                                        : Text(
                                            '天气：${weatherData['result']['realtime']['skycon']}  温度：${weatherData['result']['realtime']['temperature']}°C',
                                            style: TextStyle(color: Colors.blueGrey[800], fontSize: 18, fontWeight: FontWeight.w500),
                                          ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}
